/*
 * @Author: diana
 * @Date: 2023-05-05 21:52:34
 * @LastEditTime: 2023-05-06 19:50:35
 */
import React, { useEffect, useState } from "react";
import { ethers } from "ethers";

import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

import abi from "../../../backend/artifacts/contracts/AddressInfo.sol/AddressInfo.json";
import { Box, Button, ButtonGroup, Divider, Heading, Input, Stack,Text, Textarea } from "@chakra-ui/react";
import {
  Accordion,
  AccordionItem,
  AccordionButton,
  AccordionPanel,
  AccordionIcon,
} from '@chakra-ui/react'
declare let window: any;
function App() {
  // 合约地址abi
  const contractAddress = "0x8A791620dd6260079BF849Dc5567aDC3F2FdC318";
  //合约编译的json文件
  const contractABI = abi.abi;
  const toatTime = 2
  // 接收参数
  const [currentAccount, setCurrentAccount] = useState("");
  const [name, setName] = useState("");
  const [message, setMessage] = useState("");
  const [phone, setPhone] = useState("");

  const [allCoffee, setAllCoffee] = useState([]);

  // 检查是否连接钱包
  const checkIfWalletIsConnected = async () => {
    try {
      //window.ethereum
      const { ethereum } = window;
      // 获取当前网页连接的账户
      const accounts = await ethereum.request({ method: "eth_accounts" });

      if (accounts.length !== 0) {
        const currentAc = accounts[0];
        setCurrentAccount(currentAc);

        toast.success("Wallet is Connected", {
          position: "top-right",
          autoClose: toatTime,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
      } else {
        toast.warn("Make sure you have MetaMask Connected", {
          position: "top-right",
          autoClose: toatTime,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
      }
    } catch (e) {
      toast.error(`${e.message}`, {
        position: "top-right",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    }
  };

  // 连接钱包
  const connectWallet = async () => {
    try {
      const { ethereum } = window;
      if (!ethereum) {
        toast.warn("Make sure you have MetaMask Connected", {
          position: "top-right",
          autoClose: 5000,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });
        return;
      }
      // 申请连接，弹窗
      const account = ethereum.request({ method: "eth_requestAccounts" });
      setCurrentAccount(account[0]);
    } catch (e) {
      toast.error(`${e.message}`, {
        position: "top-right",
        autoClose: 5000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
      });
    }
  };

  // 购买
  const buyCoffee = async () => {
    try {
      const { ethereum } = window;

      if (ethereum) {
        const provider = new ethers.providers.Web3Provider(ethereum);
        // 写操作必须要signer
        const signer = provider.getSigner();

        // 合约对象
        const coffeeContract = new ethers.Contract(
          contractAddress,
          contractABI,
          signer
        );

        const coffeeTxn = await coffeeContract.addAddress(
          name ? name : "Anonyous",
          message ? message : "enjoy your coffee",
          phone ? phone : "13200000000",
          //value时调用时要传给合约的eth
          { value: ethers.utils.parseEther("0.001"), gasLimit: 400000 }
        );

        console.log("Mining...", coffeeTxn.hash);

        toast.info("Sending Fund for coffee...", {
          position: "top-left",
          autoClose: 1800,
          hideProgressBar: false,
          closeOnClick: true,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
        });

        await coffeeTxn.wait();

        console.log("Mined", coffeeTxn.hash);

        setMessage("");
        setName("");
        setPhone("");

       
      } else {
        console.log("Ethereum object doesn't exist!");
      }
    } catch (e) {
      console.log(e);
    }
  };

  // 获取已购买的数组以便展示
  const getAllCoffee = async () => {
    try {
      const { ethereum } = window;
      if (ethereum) {
        const provider = new ethers.providers.Web3Provider(ethereum);
        const signer = provider.getSigner();
        const coffeeContract = new ethers.Contract(
          contractAddress,
          contractABI,
          signer
        );
        console.log("获取地址");
        const coffees = await coffeeContract.getAddresses();

        const finalCoffees = coffees.map((item) => {
          return {
            phone: item.phone,
            name: item.name,
            message: item.message,
          };
        });
        console.log(finalCoffees);
        setAllCoffee(finalCoffees);

        console.log("------------#---------------", finalCoffees);
      } else {
        console.log("Ethereum object doesn't exist!");
      }
    } catch (e) {
      console.log(e);
    }
  };

  useEffect(() => {
    let coffeeContract;
    checkIfWalletIsConnected();

    getAllCoffee();

    // 监听时调用的函数
    // const onNewAddress = (from, name, message) => {
    //   setAllCoffee((pre) => [
    //     ...pre,
    //     {
    //       phone: item.phone,
    //         name: item.name,
    //         message: item.message,
    //     },
    //   ]);
    // };

    // if (window.ethereum) {
    //   const provider = new ethers.providers.Web3Provider(window.ethereum);
    //   const signer = provider.getSigner();

    //   coffeeContract = new ethers.Contract(
    //     contractAddress,
    //     contractABI,
    //     signer
    //   );
    //   coffeeContract.on("NewAddress", onNewAddress);
    // }

    // return () => {
    //   // 关闭订阅的监听
    //   if (coffeeContract) {
    //     coffeeContract.off("NewAddress", onNewAddress);
    //   }
    // };
  }, []);

  // 输入框值变化事件
  const handleOnMessageChange = (e) => {
    const { value } = e.target;
    setMessage(value);
  };
  const handleOnNameChange = (e) => {
    const { value } = e.target;
    setName(value);
  };
  const handlePhoneChange = (e) => {
    const { value } = e.target;
    setPhone(value);
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-screen py-1 bg-gray-100">
      <main className="flex flex-col items-center justify-center w-full flex-1 px-20 text-center">
        <h1 className="text-6xl text-green-600 mb-6">Add Address</h1>

        {currentAccount ? (
          <div className="w-full max-w-xs top-3 z-50">
            <form className="bg-white shadow-md-rounded px-8 pt-6 pb-8 mb-4">
              <div className="mb-4">
                <label
                  className="block text-gray-700 text-sm font-bold mb-2"
                  htmlFor="name"
                >
                  Name
                </label>
                <Stack spacing={3}>
  
  <Input placeholder='Coffee name' size='md'onChange={handleOnNameChange} />
</Stack>
               
              </div>

              <div className="mb-4">
                <label
                  className="block text-gray-700 text-sm font-bold mb-2"
                  htmlFor="message"
                >
                  Send the Creator a Message
                </label>
                <Stack spacing={3}>
  
  <Textarea placeholder='Leave a message for me' onChange={handleOnMessageChange} />
</Stack>
              </div>

              <div className="mb-4">
                <label
                  className="block text-gray-700 text-sm font-bold mb-2"
                  htmlFor="name"
                >
                  Name
                </label>
                <Stack spacing={3}>
  
  <Input placeholder='Phone Number' size='md'onChange={handlePhoneChange} />
</Stack>
               
              </div>

              <div className="flex items-left justify-between">
                <Button type="button" w="100%" onClick={buyCoffee}>
                  Add
                </Button>
              </div>
            </form>
          </div>
        ) : (
          <button
            className="bg-green-500 hover:bg-green-700 text-white font-vold"
            onClick={connectWallet}
          >
            connect your wallet
          </button>
        )}
      
  
        <ToastContainer
          position="top-right"
          autoClose={2000}
          hideProgressBar={false}
          newestOnTop={false}
          closeOnClick
          rtl={false}
          pauseOnFocusLoss
          draggable
          pauseOnHover
        />
      </main>
    </div>
  );
}

export default App;
